package com.iwords.android;

import com.iwords.android.WordLibsManager.WordLib;

import android.app.ListActivity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

public class ShowWordLib extends ListActivity {
	private WordLibsManager wordLibsManager;
	private static class EfficientAdapter extends BaseAdapter {
        private LayoutInflater mInflater;
        private Bitmap mIcon;
        private Bitmap mIconSet;

        public EfficientAdapter(Context context) {
            // Cache the LayoutInflate to avoid asking for a new one each time.
            mInflater = LayoutInflater.from(context);

            // Icons bound to the rows.
            mIcon = BitmapFactory.decodeResource(context.getResources(), R.drawable.book);
            mIconSet = BitmapFactory.decodeResource(context.getResources(), R.drawable.book_category);
        }

        /**
         * The number of items in the list is determined by the number of speeches
         * in our array.
         *
         * @see android.widget.ListAdapter#getCount()
         */
        public int getCount() {
            return WordLibsManager.CurrentLibs.size();
        }

        /**
         * Since the data comes from an array, just returning the index is
         * sufficent to get at the data. If we were using a more complex data
         * structure, we would return whatever object represents one row in the
         * list.
         *
         * @see android.widget.ListAdapter#getItem(int)
         */
        public Object getItem(int position) {
            return WordLibsManager.CurrentLibs.get(position);
        }

        /**
         * Use the array index as a unique id.
         *
         * @see android.widget.ListAdapter#getItemId(int)
         */
        public long getItemId(int position) {
            return position;
        }

        /**
         * Make a view to hold each row.
         *
         * @see android.widget.ListAdapter#getView(int, android.view.View,
         *      android.view.ViewGroup)
         */
        public View getView(int position, View convertView, ViewGroup parent) {
            // A ViewHolder keeps references to children views to avoid unneccessary calls
            // to findViewById() on each row.
            ViewHolder holder;

            // When convertView is not null, we can reuse it directly, there is no need
            // to reinflate it. We only inflate a new View when the convertView supplied
            // by ListView is null.
            if (convertView == null) {
                convertView = mInflater.inflate(R.layout.list_item_icon_text, null);

                // Creates a ViewHolder and store references to the two children views
                // we want to bind data to.
                holder = new ViewHolder();
                holder.text = (TextView) convertView.findViewById(R.id.wordlib_name);
                holder.icon = (ImageView) convertView.findViewById(R.id.wordlib_icon);

                convertView.setTag(holder);
            } else {
                // Get the ViewHolder back to get fast access to the TextView
                // and the ImageView.
                holder = (ViewHolder) convertView.getTag();
            }

            // Bind the data efficiently with the holder.
            holder.text.setText(WordLibsManager.CurrentLibs.get(position).libName);
            if(WordLibsManager.CurrentLibs.get(position).isLeaf){
            	holder.icon.setImageBitmap(mIcon);
            }else{
            	holder.icon.setImageBitmap(mIconSet);
            }

            return convertView;
        }

        static class ViewHolder {
            TextView text;
            ImageView icon;
        }
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        this.wordLibsManager = new WordLibsManager((IWordsApp)getApplicationContext(), this);
        //System.out.println("ShowWordLib.onCreate() WordLibs.size()="+WordLibs.size()+" CurrentLibs.size()="+CurrentLibs.size());
        setContentView(R.layout.show_word_lib);
        //System.out.println("ShowWordLib.onCreate() WordLibs.size()="+WordLibs.size()+" CurrentLibs.size()="+CurrentLibs.size());
        
        setListAdapter(new EfficientAdapter(this));
        final ListView listView = getListView();
        listView.setItemsCanFocus(false);
        listView.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
        //为ListView设置列表项点击监听器
        listView.setOnItemClickListener(new OnItemClickListener() {
                    @Override
                    public void onItemClick(AdapterView<?> parent, View view,
                            int position, long id) {
                        WordLibsManager.WordLib lib = (WordLibsManager.WordLib)parent.getItemAtPosition(position);
                    	if(lib.isLeaf){
        					Intent intent = new Intent(ShowWordLib.this, DownloadWordsLib.class);
        					intent.putExtra("currentWordLibId", lib.libId);
        					ShowWordLib.this.startActivity(intent);
                    		//displayMessage("新课本中已经记住的单词会根据单词拼写被过滤掉，直接进入[Done]队列，不再进入[新词]队列。");
                    		//new ChangeWordLib(wordLibsManager.iWordsApp, ShowWordLib.this).userSelectedWordLib(lib.libId);//复制一份课本词库到用户词库
                    		//Intent intent = new Intent(ShowWordLib.this, ProgressingActivity.class);
                    		//intent.putExtra("currentLibId", lib.libId);
                    		//ShowWordLib.this.startActivity(intent);
                    		
                    	}else{
                    		Intent intent = new Intent(ShowWordLib.this, ShowWordLib.class);
                        	intent.putExtra("selectedLibId", lib.libId);
                        	intent.putExtra("isLeaf", lib.isLeaf);
	                    	ShowWordLib.this.startActivity(intent);
                    	}
                    }
        });
        
		if(getIntent().hasExtra("currentWordLibId")){
			Long currentWordLibId = getIntent().getLongExtra("currentWordLibId", 0L);
			wordLibsManager.packSistersAsList(currentWordLibId);
			return;
		}
		
		Long pid = 0L;
		if(getIntent().hasExtra("selectedLibId")){//如果是来自词库选择流程
			pid = getIntent().getLongExtra("selectedLibId", 0L);
		}
		wordLibsManager.packChildrenAsList(pid);
    }

	public void onBackPressed(){
    	WordLib first = (WordLib)this.getListAdapter().getItem(0);
    	Long pid = wordLibsManager.getParent(first.pId);
    	if(pid == null)  { //到顶后的逻辑？？？？？？
    		//System.out.println("ShowWordLib onBackPressed() 2 pid == null");
    		super.onBackPressed();
    		return;
    	}
		//System.out.println("ShowWordLib onBackPressed() 3 pid = "+pid);
    	Intent intent = new Intent(this, ShowWordLib.class);
    	intent.putExtra("selectedLibId", pid);
    	intent.putExtra("isLeaf", false);
		//System.out.println("ShowWordLib onBackPressed() 4 parent.libId="+parent.libId+" parent.libName="+parent.libName+" parent.isLeaf="+parent.isLeaf);
		this.startActivity(intent);
		//this.finish();
    }
    
    public void onPause(){
    	super.onPause();
    	//System.out.println("ShowWordLib.onPause() this = "+this);
    	this.finish();
    }
	private void displayMessage(String message){
		Toast t1 = Toast.makeText(getApplication(), message, Toast.LENGTH_LONG*2);
		t1.show();
	}
}